const QRCode = require('qrcode');
const crypto = require('crypto');
const logger = require('../utils/logger');

class QRCodeService {
  /**
   * 生成订单二维码token
   * @param {number} orderId 订单ID
   * @param {number} userId 用户ID
   * @returns {string} 二维码token
   */
  generateOrderToken(orderId, userId) {
    const timestamp = Date.now();
    const data = `${orderId}:${userId}:${timestamp}`;
    const secret = process.env.QR_SECRET || 'default-qr-secret';
    
    // 生成签名
    const signature = crypto
      .createHmac('sha256', secret)
      .update(data)
      .digest('hex');
    
    // 组合token
    const token = Buffer.from(`${data}:${signature}`).toString('base64');
    return token;
  }

  /**
   * 验证订单二维码token
   * @param {string} token 二维码token
   * @returns {object|null} 解析结果或null
   */
  verifyOrderToken(token) {
    try {
      const decoded = Buffer.from(token, 'base64').toString('utf8');
      const parts = decoded.split(':');
      
      if (parts.length !== 4) {
        return null;
      }
      
      const [orderId, userId, timestamp, signature] = parts;
      const data = `${orderId}:${userId}:${timestamp}`;
      const secret = process.env.QR_SECRET || 'default-qr-secret';
      
      // 验证签名
      const expectedSignature = crypto
        .createHmac('sha256', secret)
        .update(data)
        .digest('hex');
      
      if (signature !== expectedSignature) {
        return null;
      }
      
      // 检查token是否过期（24小时）
      const tokenTime = parseInt(timestamp);
      const now = Date.now();
      const maxAge = 24 * 60 * 60 * 1000; // 24小时
      
      if (now - tokenTime > maxAge) {
        return null;
      }
      
      return {
        orderId: parseInt(orderId),
        userId: parseInt(userId),
        timestamp: tokenTime,
        isValid: true
      };
    } catch (error) {
      logger.error('验证二维码token失败:', error);
      return null;
    }
  }

  /**
   * 生成二维码图片
   * @param {string} data 二维码数据
   * @param {object} options 选项
   * @returns {Promise<string>} base64图片数据
   */
  async generateQRCodeImage(data, options = {}) {
    try {
      const defaultOptions = {
        type: 'image/png',
        quality: 0.92,
        margin: 1,
        color: {
          dark: '#000000',
          light: '#FFFFFF'
        },
        width: options.size || 256
      };
      
      const qrOptions = { ...defaultOptions, ...options };
      const qrCodeDataURL = await QRCode.toDataURL(data, qrOptions);
      
      // 返回base64数据（去掉data:image/png;base64,前缀）
      return qrCodeDataURL.split(',')[1];
    } catch (error) {
      logger.error('生成二维码图片失败:', error);
      throw new Error('生成二维码失败');
    }
  }

  /**
   * 生成订单二维码数据
   * @param {object} order 订单对象
   * @returns {object} 二维码数据
   */
  generateOrderQRData(order) {
    const token = this.generateOrderToken(order.id, order.userId);
    
    // 二维码包含的数据
    const qrData = {
      type: 'order',
      orderId: order.id,
      orderNumber: order.orderNumber,
      token: token,
      amount: order.finalAmount,
      status: order.status,
      timestamp: Date.now()
    };
    
    return {
      token,
      data: JSON.stringify(qrData),
      url: `${process.env.APP_URL || 'https://app.example.com'}/order/verify?token=${token}`
    };
  }

  /**
   * 验证订单二维码数据
   * @param {string} qrDataString 二维码数据字符串
   * @returns {object|null} 验证结果
   */
  verifyOrderQRData(qrDataString) {
    try {
      const qrData = JSON.parse(qrDataString);
      
      if (qrData.type !== 'order' || !qrData.token) {
        return null;
      }
      
      const tokenResult = this.verifyOrderToken(qrData.token);
      if (!tokenResult) {
        return null;
      }
      
      return {
        ...tokenResult,
        orderNumber: qrData.orderNumber,
        amount: qrData.amount,
        qrStatus: qrData.status
      };
    } catch (error) {
      logger.error('验证订单二维码数据失败:', error);
      return null;
    }
  }
}

module.exports = new QRCodeService();